import json
import os
from pydantic import Field
from enum import Enum
from typing import Optional
from dotenv import load_dotenv
from fastapi import APIRouter, Depends,Request
from pydantic import BaseModel
from sqlalchemy.orm import Session
from datetime import datetime
from ..crud.ppt_crud import delete_ppt_by_id, get_ppt_by_id
from ..crud.textbook_crud import create_textbook as create_textbook_db, delete_textbook
from ..crud.paper_crud import create_paper as create_paper_db, delete_paper
from ..crud.paper_crud import get_paper_by_id
from ..crud.textbook_crud import get_textbook_by_id
from ..crud.user_crud import get_user_by_id, get_user_by_name
from ..crud.video_crud import delete_video_by_id, get_video_by_id,create_video as create_video_db
from ..crud.voice_crud import delete_voice_by_id, get_voice_by_id
from ..database.db import get_db
from ..crud.image_crud import delete_image, get_image_by_id
from ..utils.jwt_handler import get_username
from ..crud.folder_source_crud import create_folder_source, delete_folder_source

from ..utils.file_tools import create_file_copy, delete_file

base_url=APIRouter(prefix="/utils", tags=["基本:用户资源保存和删除"])

load_dotenv()
SOURCES_PATH=os.getenv("SOURCES_PATH")

class ResoureceType(str,Enum):
    image="image"
    video="video"
    textbook="textbook"
    paper="paper"
    ppt="ppt"
    voice="voice"

class SaveParam(BaseModel):
    folder_id: int=...
    resource_type:ResoureceType=...
    resource_id:int=...
@base_url.post("/save")
async def save_source(param: SaveParam,db: Session = Depends(get_db),
                      username: str = Depends(get_username)):
    """
    # type类型
    - textbook
    - paper
    - voice
    - ppt
    - image
    - video
    """
    user=get_user_by_name(db,username)
    folder_id=param.folder_id
    resource_type=param.resource_type
    resource_id=param.resource_id
    print("resource-type",resource_type)
    result={}
    if (resource_type == ResoureceType.image or
            resource_type == ResoureceType.video or
            resource_type == ResoureceType.ppt or
            resource_type == ResoureceType.voice):
        result = create_folder_source(db, folder_id, resource_type, resource_id)
    copy_item={}
    if resource_type==ResoureceType.textbook:
        textbook_db=get_textbook_by_id(db,resource_id)
        print(textbook_db)
        textbook_path=textbook_db.get("path")
        textbook_name=textbook_db.get("name")
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        textbook_name=f"{timestamp}副本"+textbook_name
        textbook_path=textbook_db.get("path")
        textbook_starts=textbook_db.get("starts")
        textbook_subject=textbook_db.get("subject")
        textbook_grade=textbook_db.get("grade")
        textbook_cover=textbook_db.get("cover")

        # textbook_complete_path=os.path.join(SOURCES_PATH,textbook_path)
        textbook_copy_path=create_file_copy(textbook_path)
        copy_item=create_textbook_db(db,name=textbook_name,path=textbook_copy_path,type="textbook",
                                     subject=textbook_subject,grade=textbook_grade,
                                     cover=textbook_cover,starts=textbook_starts)

        result_id=copy_item.get("id")
        result=create_folder_source(db,folder_id,resource_type,result_id)
    elif resource_type==ResoureceType.paper:
        paper_db=get_paper_by_id(db,resource_id)
        paper_path=paper_db.get("path")
        paper_name=paper_db.get("name")
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        paper_name=f"{timestamp}副本"+paper_name
        paper_subject=paper_db.get("subject")
        paper_grade=paper_db.get("grade")
        paper_starts=paper_db.get("starts")
        # paper_type=paper_db.get("type")

        # paper_complete_path=os.path.join(SOURCES_PATH,paper_path)
        paper_copy_path=create_file_copy(paper_path)
        copy_item=create_paper_db(db,name=paper_name,path=paper_copy_path,type="paper",
                                  subject=paper_subject,grade=paper_grade,starts=paper_starts)
        result_id=copy_item.get("id")
        result=create_folder_source(db,folder_id,resource_type,result_id)
    return {
        "code":200,
        "data":result,
        "message":"保存成功"
    }
from ..utils.deletes_oss import main as delete_on_oss
@base_url.delete("/delete")
async def delete_source(param: SaveParam,db: Session = Depends(get_db),
                        username: str = Depends(get_username)):
    """
        # type类型
        - textbook
        - paper
        - voice
        - ppt
        - image
        - video
        """
    user=get_user_by_id(db,username)
    if param.resource_type==ResoureceType.image :
        image_db=delete_image(db,param.resource_id)
        image_path=image_db.get("path")
        delete_on_oss(image_path)
        all_path=os.path.join(SOURCES_PATH,image_path)
        delete_file(all_path)

    elif param.resource_type==ResoureceType.video :
        video_db=delete_video_by_id(db,param.resource_id)
        video_path=video_db.get("path")
        delete_on_oss(video_path)
        all_path=os.path.join(SOURCES_PATH,video_path)
        delete_file(all_path)

    elif param.resource_type==ResoureceType.ppt:
        ppt_db=delete_ppt_by_id(db,param.resource_id)
        ppt_path=ppt_db.get("path")
        delete_on_oss(ppt_path)
        all_path=os.path.join(SOURCES_PATH,ppt_path)
        delete_file(all_path)

    elif param.resource_type==ResoureceType.voice:
        voice_db=delete_voice_by_id(db,param.resource_id)
        voice_path=voice_db.get("path")
        delete_on_oss(voice_path)
        all_path=os.path.join(SOURCES_PATH,voice_path)
        delete_file(all_path)

    elif param.resource_type==ResoureceType.textbook :
        textbook_db=delete_textbook(db,param.resource_id)
        textbook_path=textbook_db.get("path")

        delete_on_oss(textbook_path)
        all_path=os.path.join(SOURCES_PATH,textbook_path)
        delete_file(all_path)

    elif param.resource_type==ResoureceType.paper:
        paper_db=delete_paper(db,param.resource_id)
        paper_path=paper_db.get("path")
        delete_on_oss(paper_path)
        all_path=os.path.join(SOURCES_PATH,paper_path)
        delete_file(all_path)

    resource_db=delete_folder_source(db,param.folder_id,param.resource_id,param.resource_type)
    return {
        "code":200,
        "data":resource_db,
        "message":"删除成功"
    }

from ..utils.file_tools import download_file
from ..utils.uploads_oss import main as upload_on_oss


@base_url.get("/onlyoffice-callback")
async def onlyoffice_callback(requests: Request, db: Session = Depends(get_db)):
    data = await requests.json()
    status = data.get("status")
    file_url = data.get("url")
    key = data.get("key")
    resource_type=key.split("-")[0]
    resource_id=key.split("-")[1]

    path=""
    if resource_type=="textbook":
        textbook_db=get_textbook_by_id(db,resource_id)
        path=textbook_db.get("path")
    elif resource_type=="paper":
        paper_db=get_paper_by_id(db,resource_id)
        path=paper_db.get("path")
    elif resource_type=="voice":
        voice_db=get_voice_by_id(db,resource_id)
        path=voice_db.get("path")
    elif resource_type=="ppt":
        ppt_db=get_ppt_by_id(db,resource_id)
        path=ppt_db.get("path")
    elif resource_type=="image":
        image_db=get_image_by_id(db,resource_id)
        path=image_db.get("path")
    elif resource_type=="video":
        video_db=get_video_by_id(db,resource_id)
        path=video_db.get("path")
    if status == 2 and file_url and key:
        # 下载 OnlyOffice 编辑后的文件
        response = requests.get(file_url)
        if response.status_code == 200:
            all_path=os.path.join(SOURCES_PATH, path)
            download_file(file_url, all_path)
            upload_on_oss(key=path,file_path=all_path)

            return {
                "error":0
            }
        else:
            return {"error": 1, "message": "下载失败"}
    else:
        return {"error": 0}